using System.Security.Claims;
using Microsoft.AspNetCore.Mvc.Filters;
using UniversalAdmin.Domain.Entities;
using UniversalAdmin.Domain.Interfaces;

namespace UniversalAdmin.Api.Filters;

public class ExceptionLogFilter : IExceptionFilter
{
  private readonly IUnitOfWork _uow;
  public ExceptionLogFilter(IUnitOfWork uow) => _uow = uow;

  public void OnException(ExceptionContext context)
  {
    var http = context.HttpContext;
    var userIdClaim = http.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;

    var log = new OperationLog
    {
      UserId = int.TryParse(userIdClaim, out var uid) ? uid : null,
      Action = "exception",
      Resource = context.ActionDescriptor.RouteValues["controller"],
      IpAddress = http.Connection.RemoteIpAddress?.ToString(),
      UserAgent = http.Request.Headers.UserAgent
    };
    _uow.OperationLogRepository.AddAsync(log).GetAwaiter().GetResult();
    _uow.SaveChangesAsync().GetAwaiter().GetResult();
  }
}